<template>
  <div class="otherHome">
    <Other-Header bgColor="#5741d9"></Other-Header>
    <div class="articleDetailsBox" :articleId="articleId">
      <!-- 面包屑crumbs-->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">{{$t('l.home')}}</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/announcement', query: {type: type} }">{{parentName}}</el-breadcrumb-item>
        <el-breadcrumb-item>{{categoryName}}</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 文章详情标题 -->
      <div class="articleDetails">
        <div class="termsInfo">
          <div class="termsInfoSearch">
            <el-input
              :placeholder="$t('l.other_a_63')"
              suffix-icon="el-input__icon el-icon-search"
              v-model="termsInfoInput"
              size="small"
              style="width:240px;"
            ></el-input>
          </div>
          <div class="advertBox">
            <i></i>
            <h3 class="advertTitle">{{$t('l.other_a_68')}}</h3>
          </div>
        </div>
        <!-- 文章详情内容 -->
        <div class="articleDetailsCon clearfix">
          <div class="leftCon">
            <ul class>
              <li
                v-for="(item,index) in articleList"
                :key="index"
                :class="{ selected: item.id==articleId }"
                @click="view(item.id)"
              >{{item.title}}</li>
            </ul>
          </div>
          <div class="mainCon">
            <h4 class="articleDetailsTitlle">{{details.title}}</h4>
            <div class="userInfo">
              <img src="../../assets/images/userlogo.png" alt class="userIcon" />
              <div class="userInfoCon" v-show="details.updateTime">
                <p class="userInfoName">{{details.author}}</p>
                <p class="userInfoDate">{{details.updateTime | TimeAgo}} · {{$t('l.other_a_69')}}</p>
              </div>
            </div>
            <div class="articleInfo" v-html="details.content"></div>
            <div class="helpFeedback" v-show="type==1">
              <h6>{{$t('l.other_a_70')}}</h6>
              <div class="helpFeedbackBtnBox">
                <div
                  class="helpFeedbackBtn"
                  :class="{active: isLike==1, disabled: !isLogin}"
                  @click="likeArticle($event, articleId, 1)"
                >
                  <span class="selectIcon"></span>{{$t('l.other_a_71')}}
                </div>
                <div
                  class="helpFeedbackBtn"
                  :class="{active: isLike==0, disabled: !isLogin}"
                  @click="likeArticle($event, articleId, 0)"
                >
                  <span class="cancelIcon"></span>{{$t('l.other_a_72')}}
                </div>
              </div>
              <p
                class="feedbackNum"
              >{{$t('l.other_a_76', [details.likeNum+details.notLikeNum, details.likeNum])}}</p>
              <p class="submitWorkOrder" v-show="isLogin">
                {{$t('l.other_a_73')}}
                <router-link to="/workManage" class="link">{{$t('l.other_a_6')}}</router-link>
              </p>
            </div>
            <div class="comment" v-show="type==1">
              <p class>{{$t('l.other_a_74')}}</p>
              <span>{{$t('l.other_a_75')}}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <Footer></Footer>
  </div>
</template>

<script>
import { api } from "@/api/api";
import OtherHeader from "@/components/otherHeader";
import Footer from "@/components/footer";

let timeLang;
function timeago(dateTimeStamp, timeLang) {
  if(!dateTimeStamp || !timeLang) return;
  var minute = 1000 * 60; 
  var hour = minute * 60;
  var day = hour * 24;
  var week = day * 7;
  var halfamonth = day * 15;
  var month = day * 30;
  var now = new Date().getTime(); 
  var diffValue = now - dateTimeStamp; //时间差
  var result;

  if (diffValue < 0) {
    return;
  }
  var minC = diffValue / minute; //计算时间差的分，时，天，周，月
  var hourC = diffValue / hour;
  var dayC = diffValue / day;
  var weekC = diffValue / week;
  var monthC = diffValue / month;
  if (monthC >= 1 && monthC <= 3) {
    result = " " + parseInt(monthC) + timeLang.MATHAGO;
  } else if (weekC >= 1 && weekC <= 3) {
    result = " " + parseInt(weekC) + timeLang.WEEKAGO;
  } else if (dayC >= 1 && dayC <= 6) {
    result = " " + parseInt(dayC) + timeLang.DAYAGO;
  } else if (hourC >= 1 && hourC <= 23) {
    result = " " + parseInt(hourC) + timeLang.HOURAGO;
  } else if (minC >= 1 && minC <= 59) {
    result = " " + parseInt(minC) + timeLang.MINUTEAGO;
  } else if (diffValue >= 0 && diffValue <= minute) {
    result = timeLang.SECONDSAGO;
  } else {
    var datetime = new Date();
    datetime.setTime(dateTimeStamp);
    var Nyear = datetime.getFullYear();
    var Nmonth =
      datetime.getMonth() + 1 < 10
        ? "0" + (datetime.getMonth() + 1)
        : datetime.getMonth() + 1;
    var Ndate =
      datetime.getDate() < 10 ? "0" + datetime.getDate() : datetime.getDate();
    var Nhour =
      datetime.getHours() < 10
        ? "0" + datetime.getHours()
        : datetime.getHours();
    var Nminute =
      datetime.getMinutes() < 10
        ? "0" + datetime.getMinutes()
        : datetime.getMinutes();
    var Nsecond =
      datetime.getSeconds() < 10
        ? "0" + datetime.getSeconds()
        : datetime.getSeconds();
    result = Nyear + "-" + Nmonth + "-" + Ndate;
  }
  return result;
}

export default {
  components: {
    OtherHeader,
    Footer
  },
  data() {
    timeLang = {
      MATHAGO: this.$t('l.other_a_83'),
      WEEKAGO: this.$t('l.other_a_84'),
      DAYAGO: this.$t('l.other_a_85'),
      HOURAGO: this.$t('l.other_a_86'),
      MINUTEAGO: this.$t('l.other_a_87'),
      SECONDSAGO: this.$t('l.other_a_88')
    }
    return {
      isLogin: this.$store.state.usertoken ? true : false,
      categoryName: "",
      parentName: "",
      termsInfoInput: "",
      details: {},
      articleList: [],
      isLike: -1,
      type: ""
    };
  },
  // 声明一个本地的过滤器
  filters: {
    TimeAgo: function(value) {
      return timeago(new Date(value), timeLang);
    }
  },
  computed: {
    articleId() {
      return this.$route.query.articleId;
    },
    userCode() {
      return this.isLogin ? this.$store.state.userintro.userCode : null;
    }
  },
  watch: {
    type(val) {
      if (this.articleTypeMap && this.parentId) {
        // this.parentName = this.articleTypeMap[this.parentId].typeName;
        this.parentName = val == 0 ? this.$t('l.other_a_0') : this.$t('l.other_a_4');
        this.categoryName = this.articleTypeMap[this.typeId].typeName;
      }
    },
    articleId(newVal, oldVal) {
      if (newVal != oldVal) {
        this.getAnnouncementInfo(newVal);

        if (this.userCode) {
          this.updateLike(this.userCode, this.articleId);
        }
      }
    }
  },
  created() {
    this.init();
    if (this.userCode) {
      this.updateLike(this.userCode, this.articleId);
    }
  },
  methods: {
    async init() {
      await this.getAllArticleType();
      await this.getAnnouncementInfo(this.articleId);
      this.getAnnouncementList(this.typeCode);
      this.getArticleType(this.typeCode);
    },
    // 查看相关文章
    view(articleId) {
      this.$router.push({
        path: "/articleDetails",
        query: {
          articleId
        }
      });
    },
    // 更新点赞信息
    updateLike(userCode, articleId) {
      let like = localStorage.getItem("announcement.like");
      try {
        like = JSON.parse(like) || [];
      } catch (error) {
        like = [];
      }
      let likeItem = like.filter(item => {
        return item.userCode == userCode && item.articleId == articleId;
      });

      if (likeItem.length) {
        this.isLike = likeItem[0].isLike;
      } else {
        this.isLike = -1;
      }
    },
    // 对文章点赞和不点赞
    async likeArticle(e, articleId, isLike) {
      if (e.target.className.includes("disabled") || this.isLike != -1) return;

      let res = await api.postAnnouncementLike(articleId, {
        isLike: isLike
      });
      let { code, data, msg } = res.data;

      if (code == 0) {
        let like = localStorage.getItem("announcement.like");
        try {
          like = JSON.parse(like) || [];
        } catch (error) {
          like = [];
        }
        like.push({
          articleId: articleId,
          isLike: isLike,
          userCode: this.userCode
        });

        if (isLike == 1) {
          this.details.likeNum += 1;
        } else {
          this.details.notLikeNum += 1;
        }
        this.isLike = isLike;

        localStorage.setItem("announcement.like", JSON.stringify(like));
      } else {
        this.$layer.msg(msg);
      }
    },
    // 获取此组别文章列表
    async getAnnouncementList(typeCode) {
      let params = {
        lang: "zh_CN",
        pageNum: 1,
        pageSize: 10,
        typeCode: typeCode
      };
      let res = await api.announcementList(params);
      let { code, data, msg } = res.data;

      if (code == 0) {
        this.articleList = data.records;
      } else {
        this.$layer.msg(msg);
      }
    },
    // 获取当前文章详情
    async getAnnouncementInfo(articleId) {
      let res = await api.announcementInfo(articleId);
      let { code, data, msg } = res.data;

      if (code == 0) {
        this.details = Object.assign({}, data);
        // this.categoryName = data.categoryName;
        this.typeId = data.category;
        this.typeCode = this.articleTypeMap[data.category].typeCode;
      } else {
        this.$layer.msg(msg);
      }
    },
    // 获取所有资讯类别
    async getAllArticleType() {
      let typeMap = {};
      let res = await api.allArticleType({
        lang: "zh_CN"
      });
      let { code, data, msg } = res.data;

      if (code == 0) {
        data.forEach(element => {
          typeMap[element.id] = {
            typeCode: element.typeCode,
            typeName: element.typeName
          };
        });
        this.articleTypeMap = typeMap;
      } else {
        this.$layer.msg(msg);
      }
    },
    // 获取资讯类别
    async getArticleType(typeCode) {
      if (!typeCode) return false;

      let res = await api.articleType({
        lang: "zh_CN",
        typeCode: typeCode
      });
      let { code, data, msg } = res.data;

      if (code == 0) {
        this.parentId = data.parentId;
        this.type = data.parentId == 20 ? 0 : 1;
        // this.parentName = this.articleTypeMap[data.parentId];
      } else {
        this.$layer.msg(msg);
        return false;
      }
    }
  }
};
</script>

<style lang="less" scoped>
.otherHome {
  background-color: #f7f8fc;
  position: absolute;
  min-height: 100%;
  width: 100%;
  padding-top: 100px;
}
.articleDetailsBox {
  width: 1200px;
  box-sizing: border-box;
  margin: 2px auto 0;
  padding-bottom: 160px;
  overflow: hidden;

  /* 面包屑 */
  /deep/.el-breadcrumb__inner a,
  /deep/.el-breadcrumb__inner.is-link {
    height: 60px;
    line-height: 60px;
    font-size: 16px;
    font-familyA: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(51, 56, 94, .5);
  }
  /deep/span.el-breadcrumb__item:last-child span {
    height: 60px;
    line-height: 60px;
    font-size: 16px;
    font-familyA: PingFangSC-Regular;
    font-weight: 400;
    color: #2D8DFE;
  }
  /* 内容 */
  .articleDetails {
    width: 1200px;
    min-height: 924px;
    background: #fff;
    padding: 36px 40px 80px;
    box-sizing: border-box;
    .advertBox {
      position: relative;
      overflow: hidden;
      .advertTitle {
        display: inline-block;
        font-size: 24px;
        font-familyA: PingFangSC-Semibold;
        font-weight: 600;
        color: rgba(51, 56, 94, 1);
        line-height: 33px;
        margin-left: 20px;
        vertical-align: top;
      }
      i {
        position: absolute;
        width: 3px;
        height: 16px;
        background: #2D8DFE;
        border-radius: 2px;
        color: #33385e;
        top: 50%;
        transform: translateY(-50%);
        -webkit-transform: translateY(-50%);
      }
    }
    .termsInfoSearch {
      float: right;
    }
    .articleDetailsCon {
      margin-top: 26px;
      overflow: hidden;
      .leftCon {
        float: left;
        width: 219px;
        min-height: 100px;
        margin-right: 97px;
        .selected {
          background: #2D8DFE;
          border-radius: 6px;
          color: #fff;
        }
        ul li {
          // margin-top: 40px;
          font-size: 16px;
          font-familyA: PingFangSC-Regular;
          font-weight: 400;
          color: rgba(51, 56, 94, 1);
          line-height: 26px;
          padding: 23px 17px;
          box-sizing: border-box;
          cursor: pointer;
        }
      }
      .mainCon {
        overflow: hidden;
        width: 737px;
        .articleDetailsTitlle {
          font-size: 30px;
          font-familyA: PingFangSC-Medium;
          font-weight: 500;
          color: rgba(51, 56, 94, 1);
          line-height: 42px;
        }
        .userInfo {
          margin: 20px 0 37px 0;
          .userIcon {
            display: inline-block;
            vertical-align: top;
            width: 60px;
            height: 60px;
            margin-right: 12px;
          }
          .userInfoCon {
            display: inline-block;
            vertical-align: top;
          }
          .userInfoName {
            font-size: 14px;
            font-familyA: PingFangSC-Regular;
            font-weight: 400;
            color: rgba(51, 56, 94, 1);
            line-height: 20px;
            margin: 3px 0 4px 0;
          }
          .userInfoDate {
            font-size: 12px;
            font-familyA: PingFangSC-Regular;
            font-weight: 400;
            color: rgba(51, 56, 94, 1);
            line-height: 17px;
          }
        }

        .helpFeedback {
          padding: 18px 0;
          text-align: center;
          border-top: 1px solid #f0f2fd;
          h6 {
            font-size: 16px;
            font-familyA: PingFangSC-Medium;
            font-weight: 500;
            color: rgba(51, 56, 94, 1);
            line-height: 22px;
            text-align: center;
          }
          .helpFeedbackBtnBox {
            text-align: center;
            font-size: 0;
            margin: 13px 0;
            .helpFeedbackBtn {
              display: inline-block;
              vertical-align: top;
              width: 110px;
              height: 40px;
              border-radius: 4px;
              border: 1px solid rgba(51, 56, 94, 1);
              font-size: 14px;
              font-familyA: PingFangSC-Regular;
              font-weight: 400;
              color: rgba(51, 56, 94, 1);
              line-height: 40px;
              cursor: pointer;
              &:nth-child(1) {
                margin-right: 30px;
              }
              &.active {
                border-color: transparent;
                background: #2D8DFE;
                color: #fff;
              }
              &.disabled {
                opacity: 0.38;
                cursor: not-allowed;
              }
              .selectIcon {
                display: inline-block;
                vertical-align: middle;
                width: 16px;
                height: 16px;
                background: url(../../assets/images/select.png) no-repeat left
                  center;
                margin-right: 2px;
              }
              &.active .selectIcon {
                background: url(../../assets/images/select2.png) no-repeat left
                  center;
              }
              .cancelIcon {
                display: inline-block;
                vertical-align: middle;
                width: 16px;
                height: 16px;
                background: url(../../assets/images/cancel.png) no-repeat left
                  center;
                margin-right: 2px;
              }
              &.active .cancelIcon {
                background: url(../../assets/images/cancel2.png) no-repeat left
                  center;
              }
            }
          }
          .feedbackNum {
            font-size: 14px;
            font-familyA: PingFangSC-Regular;
            font-weight: 400;
            color: rgba(51, 56, 94, 0.5);
            line-height: 20px;
            margin-bottom: 26px;
          }
          .submitWorkOrder {
            font-size: 16px;
            font-familyA: PingFangSC-Regular;
            font-weight: 400;
            color: rgba(51, 56, 94, 1);
            line-height: 22px;
            .link {
              color: #2D8DFE;
            }
          }
        }
        .comment {
          padding: 20px 0;
          text-align: left;
          border-top: 1px solid #f0f2fd;
          p {
            font-size: 16px;
            font-familyA: PingFangSC-Medium;
            font-weight: 500;
            color: rgba(51, 56, 94, 1);
            line-height: 22px;
            margin-bottom: 8px;
          }
          span {
            font-size: 14px;
            font-familyA: PingFangSC-Regular;
            font-weight: 400;
            color: rgba(51, 56, 94, 0.5);
            line-height: 20px;
          }
        }
      }
    }
  }
  /deep/.articleInfo {
    font-size: 14px;
    font-familyA: PingFangSC-Regular;
    font-weight: 400;
    color: rgba(51, 56, 94, 1);
    line-height: 26px;
    padding-bottom: 50px;
    p,
    span {
      font-size: inherit;
      font-weight: inherit;
    }
    img {
      max-width: 100%;
    }
  }
}
</style>